using Core.SimpleTemp.Application;
using Core.SimpleTemp.Common.Authorization;
using Core.SimpleTemp.Common.PagingQuery;
using Core.SimpleTemp.Mvc.Api.Internal;
using Core.Toolkit.Authorization;
using Core.Toolkit.Core;
using Core.Toolkit.Core.Api;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
using System.Linq;
using System.Collections.Generic;
using Microsoft.AspNetCore.Http;
using Core.SimpleTemp.Application.UserApp;

namespace Core.SimpleTemp.Api.Api
{
    /// <summary>
    /// JG_PersonalSafety
    ///</summary>
    [ApiExplorerSettings(GroupName = "Sys")]//swagger分类标签
    [Route("api/[controller]")]//路由说明
    [EnableCors("any")]//跨域规则
    [ApiController]//APi标识Controller
    [Authorize]//验证是否登录
    public class JG_PersonalSafetyController : CoreApiController
    {
        private readonly JG_PersonalSafetyService _service;
        private readonly SysUserAppService _sysUserService;
        private readonly JG_PersonalSafetyDetailService _serviceD;
        /// <summary>
        /// JG_PersonalSafety
        ///</summary>
        public JG_PersonalSafetyController(JG_PersonalSafetyService service, SysUserAppService sysUserService, JG_PersonalSafetyDetailService serviceD)
        {
            _service = service;
            _sysUserService = sysUserService;
            _serviceD = serviceD;
        }

        #region 基础增删改查
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetList")]
        [PermissionFilter(nameof(JG_PersonalSafetyController) + "_" + nameof(JG_PersonalSafetyController.GetList), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetList(PagingModel<JG_PersonalSafetyDto>
                pagingQueryModel)
        {
            IPageModel<JG_PersonalSafetyDto>
                result;
            result = await _service.GetList(pagingQueryModel);
            return this.JsonSuccess(result);
        }
        /// <summary>
        /// 查询
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("GetListUser")]
        [PermissionFilter(nameof(JG_PersonalSafetyController) + "_" + nameof(JG_PersonalSafetyController.GetListUser), AuthorizationConst.LIST)]
        public async Task<IActionResult>
            GetListUser(PagingModel<JG_PersonalSafetyDto>
                pagingQueryModel)
        {
            IPageModel<JG_PersonalSafetyDto>
                result;
            pagingQueryModel.Model.CreateUser= UserIdentity.Id;
            result = await _service.GetList(pagingQueryModel);
            return this.JsonSuccess(result);
        }
        /// <summary>
        /// 添加/修改
        ///</summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("Save")]
        [PermissionFilter(nameof(JG_PersonalSafetyController) + "_" + nameof(JG_PersonalSafetyController.SaveAsync), AuthorizationConst.SAVE)]
        public async Task<IActionResult>
            SaveAsync(JG_PersonalSafetyDto dto)
        {
            
            if(dto.State=="2" || dto.State == "3")
            {
                dto.ApproveID= UserIdentity.Id;
                dto.ApproveDate = DateTime.Now;
            }
            //添加
            if (Equals(dto.Id, Guid.Empty))
            {
                var UserDuty = await _sysUserService.GetUserDutyAsync(UserIdentity.Id);
                dto.UserID = UserIdentity.Id;
                dto.CreateFactory = UserIdentity.Factory;               
                if (UserDuty.Count == 0) {
                    await _service.InsertAsync(dto);
                    
                }
                else{
                    for (int i = 0; i < UserDuty.Count; i++)
                    {
                        var dto1 = dto;
                        //缺少添加部门
                        dto1.CreateDept = UserDuty[i].SysDepartmentDuty.SysDepartmentID;
                        await _service.InsertAsync(dto1);
                    }
                   
                }
                return this.JsonSuccess(string.Empty);


            }
            else
            {
                var list = dto.JG_PersonalSafetyDetail.ToList();

                dto.JG_PersonalSafetyDetail.Clear();
                //await _service.Update(dto);
                await _service.UpdateAsync(dto);
                for (int i = 0; i < list.Count; i++)
                {
                    list[i].PersonalSafetyId = dto.Id;
                    if (list[i].CreateTime == null || Equals(list[i].Id, Guid.Empty))
                    {
                        await _serviceD.InsertAsync(list[i]);
                    }
                    else
                    {
                        await _serviceD.UpdateAsync(list[i]);
                    }
                }

                //await _service.UpdateAsync(dto);
                return this.JsonSuccess(string.Empty);
            }
        }

        /// <summary>
        /// DeleteMuti
        ///</summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("DeleteMuti")]
        [PermissionFilter(nameof(JG_PersonalSafetyController) + "_" + nameof(JG_PersonalSafetyController.DeleteMutiAsync), AuthorizationConst.DELETE)]
        public async Task<IActionResult>
            DeleteMutiAsync([FromBody]Guid[] ids)
        {

            await _service.DeleteBatchAsync(ids);
            return this.JsonSuccess();
        }


        /// <summary>
        /// 根据ID获取信息
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>

        [HttpGet("Get")]
        public async Task<IActionResult>
            Get(Guid id)
        {
            var model = await _service.GetAsync(id);
            if (model == null) return this.JsonFaild("未找到对应数据:" + id);

            model.JG_PersonalSafetyDetail = model.JG_PersonalSafetyDetail.Where(m => !m.IsDeleted).ToList();
            return this.JsonSuccess(model);
        }


        /// <summary>
        /// 导出
        ///</summary>
        /// <param name="pagingQueryModel"></param>
        /// <returns></returns>

        [HttpPost("Export")]
        [PermissionFilter(nameof(JG_PersonalSafetyController) + "_" + nameof(JG_PersonalSafetyController.Export), AuthorizationConst.EXPORT)]
        public async Task<IActionResult>
            Export(PagingModel<JG_PersonalSafetyDto>
                pagingQueryModel)
        {
            var fileName = await _service.Export(pagingQueryModel);
            if (string.IsNullOrWhiteSpace(fileName))
                return this.JsonFaild(NULL_DATA_FOR_EXCEL_EXPORT);
            return this.JsonSuccess(fileName);
        }
        #endregion
//        /// <summary>
//        /// 导入
//        /// </summary>
//        /// <param name="data"></param>
//        /// <param name="file"></param>
//        /// <returns></returns>
//        [HttpPost("Import")]
//        //[PermissionFilter(nameof(FX_EquipmentFacilitiesController) + "_" + "导入")]
//        public async Task<IActionResult> ImportAsync([FromForm]String data, [FromForm]List<IFormFile> file)
//        {
//            var retMeg = await _service.ImportAsync(file[0], data);
//            if (!retMeg.Any())
//            {
//                return this.JsonSuccess();
//            }
//            else
//            {
//                return this.JsonFaild(retMeg[0].ToString());
//            }
//        }
//#endregion

    }
}